// pages/mine/chatHistory/chatHistory.js
let api = require("../../../config/api");
let utils = require("../../../utils/util");

// 本页内部工具函数：将秒级时间戳格式化为 YYYY-MM-DD HH:mm:ss（避免 this 绑定问题）
const formatTimestamp = function(seconds) {
    try {
        const d = new Date(seconds * 1000);
        const pad = (n) => (n < 10 ? '0' + n : '' + n);
        const y = d.getFullYear();
        const m = pad(d.getMonth() + 1);
        const day = pad(d.getDate());
        const hh = pad(d.getHours());
        const mm = pad(d.getMinutes());
        const ss = pad(d.getSeconds());
        return `${y}-${m}-${day} ${hh}:${mm}:${ss}`;
    } catch (_) {
        return '';
    }
}

Page({

    /**
     * 页面的初始数据
     */
    data: {
        // Tab切换状态
        activeTab: 'dialog', // 'dialog'(智能对话) 或 'image'(智能生图)
        
        // 智能对话数据
        dialogLoading: false,
        dialogHasMore: true,
        dialogLastId: null,
        dialogConversations: [],
        
        // 智能生图数据
        imageLoading: false,
        imageHasMore: true,
        imageLastId: null,
        imageConversations: [],
        
        userModelId: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.bootstrap();
    },

    bootstrap() {
        let that = this;
        utils.isLogin(function(){
            wx.showLoading();
            utils.request(api.getUserInfo, {}, 'POST')
                .then(function(res){
                    wx.hideLoading();
                    if (res.code == 0) {
                        const info = res.data || {};
                        const modelId = info.modelUserId ? String(info.modelUserId) : '';
                        that.setData({ userModelId: modelId }, () => {
                            that.resetAndLoad();
                        });
                    } else {
                        wx.showToast({ title: res.message || '获取用户信息失败', icon: 'none' });
                    }
                })
                .catch(function(e){
                    wx.hideLoading();
                    wx.showToast({ title: e || '网络异常', icon: 'none' });
                });
        });
    },

    resetAndLoad() {
        const tab = this.data.activeTab;
        if (tab === 'dialog') {
            this.setData({ dialogConversations: [], dialogLastId: null, dialogHasMore: true }, () => {
                this.loadMore('dialog');
            });
        } else {
            this.setData({ imageConversations: [], imageLastId: null, imageHasMore: true }, () => {
                this.loadMore('image');
            });
        }
    },
    
    // Tab切换
    switchTab(e) {
        const tab = e.currentTarget.dataset.tab;
        if (this.data.activeTab === tab) return;
        this.setData({ activeTab: tab }, () => {
            // 切换tab时，如果对应的数据为空，则加载数据
            if (tab === 'dialog' && this.data.dialogConversations.length === 0) {
                this.resetAndLoad();
            } else if (tab === 'image' && this.data.imageConversations.length === 0) {
                this.resetAndLoad();
            }
        });
    },

    // 加载下一页会话列表（默认每次20条）
    loadMore(tabType) {
        const tab = tabType || this.data.activeTab;
        const isDialog = tab === 'dialog';
        const loadingKey = isDialog ? 'dialogLoading' : 'imageLoading';
        const hasMoreKey = isDialog ? 'dialogHasMore' : 'imageHasMore';
        const lastIdKey = isDialog ? 'dialogLastId' : 'imageLastId';
        const conversationsKey = isDialog ? 'dialogConversations' : 'imageConversations';
        
        if (this.data[loadingKey] || !this.data[hasMoreKey]) return;
        if (!this.data.userModelId) return;
        
        // 设置对应的loading状态
        this.setData({ [loadingKey]: true });

        if (isDialog) {
            // 智能对话：使用Dify的conversations接口
            this.loadDialogConversations(loadingKey, hasMoreKey, lastIdKey, conversationsKey);
        } else {
            // 智能生图：使用后台的searchUserPicChatList接口
            this.loadImageConversations(loadingKey, hasMoreKey, lastIdKey, conversationsKey);
        }
    },

    // 加载智能对话会话列表（使用Dify接口）
    loadDialogConversations(loadingKey, hasMoreKey, lastIdKey, conversationsKey) {
        const base = api.dify && api.dify.base ? api.dify.base : '';
        const url = base + '/conversations';
        const apiKey = api.dify.dialogApiKey;
        const headers = {
            'Authorization': 'Bearer ' + apiKey
        };
        const params = {
            user: this.data.userModelId,
            limit: 20
        };
        if (this.data[lastIdKey]) params.last_id = this.data[lastIdKey];

        wx.request({
            url: url,
            method: 'GET',
            header: headers,
            data: params,
            success: (res) => {
                try {
                    if (res.statusCode === 200 && res.data && Array.isArray(res.data.data)) {
						const list = (res.data.data || []).map((it) => {
							return Object.assign({}, it, {
								formattedCreatedAt: (typeof it.created_at === 'number' && it.created_at > 0) ? formatTimestamp(it.created_at) : ''
							});
						});
                        const merged = [...this.data[conversationsKey], ...list];
                        const lastId = list.length > 0 ? list[list.length - 1].id : this.data[lastIdKey];
                        const hasMore = !!res.data.has_more;
                        
                        const updateData = {};
                        updateData[conversationsKey] = merged;
                        updateData[lastIdKey] = lastId;
                        updateData[hasMoreKey] = hasMore;
                        updateData[loadingKey] = false;
                        
                        this.setData(updateData);
                    } else {
                        const updateData = {};
                        updateData[loadingKey] = false;
                        updateData[hasMoreKey] = false;
                        this.setData(updateData);
                        console.warn('conversations unexpected response', res);
                    }
                } catch (e) {
                    const updateData = {};
                    updateData[loadingKey] = false;
                    this.setData(updateData);
                    console.warn('parse conversations failed', e);
                }
            },
            fail: (err) => {
                const updateData = {};
                updateData[loadingKey] = false;
                this.setData(updateData);
                wx.showToast({ title: '加载失败', icon: 'none' });
            }
        });
    },

    // 加载智能生图会话列表（使用后台接口）
    loadImageConversations(loadingKey, hasMoreKey, lastIdKey, conversationsKey) {
        const params = {
            pageNum: 1,
            pageSize: 20
        };
        
        // 如果有lastId，计算页码（这里简化处理，实际可能需要根据后台接口调整）
        if (this.data[lastIdKey]) {
            const currentPage = Math.floor(this.data[conversationsKey].length / 20) + 1;
            params.pageNum = currentPage;
        }

        utils.request(api.searchUserPicChatList, params, 'POST')
            .then((res) => {
                try {
                    if (res.code === "0" && res.data && Array.isArray(res.data)) {
                        const list = (res.data || []).map((it) => {
                            // 处理任务状态
                            const status = it.status || '2'; // 如果status为空，按已完成处理
                            let statusText = '已完成';
                            
                            switch (status) {
                                case '0':
                                    statusText = '待处理';
                                    break;
                                case '1':
                                    statusText = '进行中';
                                    break;
                                case '2':
                                    statusText = '已完成';
                                    break;
                                case '3':
                                    statusText = '失败';
                                    break;
                                default:
                                    statusText = '已完成'; // 默认按已完成处理
                            }
                            
                            return {
                                id: it.id,
                                name: it.queryWord || '未命名会话',
                                formattedCreatedAt: it.chatFinishTime ? formatTimestamp(new Date(it.chatFinishTime).getTime() / 1000) : '',
                                type: 'image', // 标记为智能生图类型
                                oldPictureFileName: it.oldPictureFileName || '',
                                newPictureFileName: it.newPictureFileName || '',
                                conversationId: it.conversationId || '',
                                conversationFileObjectId: it.conversationFileObjectId || '',
                                status: status, // 任务状态
                                statusText: statusText, // 状态文本
                                chatResponseContent: it.chatResponseContent || '' // AI响应内容
                            };
                        });
                        
                        const merged = [...this.data[conversationsKey], ...list];
                        const hasMore = res.data && res.data.length >= 20;
                        
                        const updateData = {};
                        updateData[conversationsKey] = merged;
                        updateData[hasMoreKey] = hasMore;
                        updateData[loadingKey] = false;
                        
                        this.setData(updateData);
                    } else {
                        const updateData = {};
                        updateData[loadingKey] = false;
                        updateData[hasMoreKey] = false;
                        this.setData(updateData);
                        console.warn('searchUserPicChatList unexpected response', res);
                    }
                } catch (e) {
                    const updateData = {};
                    updateData[loadingKey] = false;
                    this.setData(updateData);
                    console.warn('parse searchUserPicChatList failed', e);
                }
            })
            .catch((err) => {
                const updateData = {};
                updateData[loadingKey] = false;
                this.setData(updateData);
                wx.showToast({ title: '加载失败', icon: 'none' });
            });
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.resetAndLoad();
        wx.stopPullDownRefresh();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.loadMore();
    },

    // 列表项点击：跳转到zhengce页面（智能对话/智能生图）
    onItemTap(e) {
        const id = e.currentTarget.dataset.id;
        const name = e.currentTarget.dataset.name || '';
        const type = e.currentTarget.dataset.type || this.data.activeTab;
        if (!id) return;
        
        if (type === 'dialog') {
            // 智能对话：跳转到zhengce页面继续对话
            this.handleDialogItemTap(id, name);
        } else {
            // 智能生图：跳转到zhengce页面回显历史记录
            this.handleImageItemTap(e);
        }
    },

    // 处理查看按钮点击（智能生图已完成记录）
    onViewButtonTap(e) {
        // 调用智能生图处理方法
        this.handleImageItemTap(e);
    },

    // 处理智能对话item点击
    handleDialogItemTap(id, name) {
        try {
            console.log('保存智能对话历史会话参数:');
            console.log('id:', id);
            console.log('name:', name);
            
            wx.setStorageSync('historyConversationId', id);
            wx.setStorageSync('historyName', name);
            wx.setStorageSync('fromHistory', 'true');
            wx.setStorageSync('historyType', 'dialog'); // 标记为智能对话类型
            
            console.log('参数已保存到本地存储');
            
            wx.switchTab({
                url: '/pages/zhengce/zhengce',
                success: () => {
                    console.log('成功跳转到zhengce页面');
                },
                fail: (err) => {
                    console.error('跳转失败:', err);
                    wx.showToast({
                        title: '跳转失败',
                        icon: 'none'
                    });
                }
            });
        } catch (error) {
            console.error('保存参数失败:', error);
            wx.showToast({
                title: '参数保存失败',
                icon: 'none'
            });
        }
    },

    // 处理智能生图item点击
    handleImageItemTap(e) {
        const item = e.currentTarget.dataset;
        // 注意：WXML中的data-属性会被转换为小写，需要使用对应的驼峰命名
        const { id, name, oldpicturefilename, newpicturefilename, conversationid, conversationfileobjectid, status, chatresponsecontent } = item;
        
        // 转换为驼峰命名
        const oldPictureFileName = oldpicturefilename;
        const newPictureFileName = newpicturefilename;
        const conversationId = conversationid;
        const conversationFileObjectId = conversationfileobjectid;
        const taskStatus = status;
        const chatResponseContent = chatresponsecontent;
        
        try {
            console.log('保存智能生图历史会话参数:');
            console.log('id:', id);
            console.log('name:', name);
            console.log('oldPictureFileName:', oldPictureFileName);
            console.log('newPictureFileName:', newPictureFileName);
            console.log('conversationId:', conversationId);
            console.log('conversationFileObjectId:', conversationFileObjectId);
            console.log('taskStatus:', taskStatus);
            console.log('chatResponseContent:', chatResponseContent);
            
            // 保存基础参数
            wx.setStorageSync('historyConversationId', conversationId || '');
            wx.setStorageSync('historyName', name);
            wx.setStorageSync('fromHistory', 'true');
            wx.setStorageSync('historyType', 'image'); // 标记为智能生图类型
            wx.setStorageSync('historyOldPictureFileName', oldPictureFileName || '');
            wx.setStorageSync('historyNewPictureFileName', newPictureFileName || '');
            wx.setStorageSync('historyConversationFileObjectId', conversationFileObjectId || '');
            
            // 保存任务状态和AI响应内容
            wx.setStorageSync('historyTaskStatus', taskStatus || '2');
            wx.setStorageSync('historyChatResponseContent', chatResponseContent || '');
            
            console.log('智能生图参数已保存到本地存储');
            
            wx.switchTab({
                url: '/pages/zhengce/zhengce',
                success: () => {
                    console.log('成功跳转到zhengce页面');
                },
                fail: (err) => {
                    console.error('跳转失败:', err);
                    wx.showToast({
                        title: '跳转失败',
                        icon: 'none'
                    });
                }
            });
        } catch (error) {
            console.error('保存智能生图参数失败:', error);
            wx.showToast({
                title: '参数保存失败',
                icon: 'none'
            });
        }
    }
})